import {
    viewInit,
    setStepLoader,
    setStepLoaderEnd,
    initStepLoader,
    initStep2View,
    emptyInfo,
    processingData,
    addResultCells
} from './faceView.js';

import {
    getConfig
} from './wxConfig.js';
import {
    errorDialog
} from "../components/errorDialog.js";

var query = require("./query.js");
var personallInfo = require("./personalInfo.js");
var localId, serverId;
var validate_data = '';
var id_no, username, phone;
var $submit_btn, $phone;
var errorObject;
window.step = 0;
var seralNo;
jQuery(document).ready(function($) {
    if (location.hash == "#info") {
        showStepN(1);
    } else {
        showStepN(0);
    }
    viewInit();
    initValue();
    query.initQuery();
    getConfig(getAppidSignServlet, {
        "url": location.href
    }, ['chooseImage', 'uploadImage', 'downloadImage', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'uploadVoice', 'chooseVideo', 'uploadVideo', 'downloadVideo']);

    wx.ready(function() {
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。
        //对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        wx.hideOptionMenu(); // 隐藏右上角分享功能
        wx.hideAllNonBaseMenuItem();

    });
    wx.error(function(res) {
        alert("信息验证失败会执行");
    });
    bindEvent();
    $.post(homeServlet, {}, function(hdata) {
        if (hdata.code == "0000" && hdata.data) {
            $(".user-name").text(hdata.data.userName);
            if (hdata.data.phoneNo && hdata.data.phoneNo != null && hdata.data.phoneNo != "null" && hdata.data.phoneNo != "undefind") {
                $("#user-phone").text(hdata.data.phoneNo);
            }

        }
    });
    personallInfo.initPersonal();

});


// 显示第几步
function showStepN(stepNum) {
    $("#step0").hide();
    $("#step1").hide();
    $("#step2").hide();
    $("#step3").hide();
    $("#step4").hide();
    $("#step5").hide();
    if (stepNum == 1) {
        $("#step1").show();
    } else if (stepNum == 2) {
        $("#step2").show();
    } else if (stepNum == 3) {
        $("#step3").show();
    } else if (stepNum == 4) {
        $("#step4").show();
    } else if (stepNum == 5) {
        $("#step5").show();
    } else {
        $("#step0").show();
    }
}

// 下一步
function submitFuc() {
    $("#step1 input").blur();
    if ($submit_btn.hasClass("weui-btn_disabled")) {
        errorObject.showErroDialog("请填写信息");
        return;
    } else {


        getCheckNum();
    }
}

/*返回上一步*/
function fhStep() {
    var tostep = $(this).data("tostep");
    if (tostep == "0") {
        $("#step1").hide();
        $("#step4").hide();
        $("#step5").hide();
        $("#step0").show();
        emptyInfo();
    } else if (tostep == "1") {
        $("#step2").hide();
        $("#step1").show();
    } else if (tostep == "1") {
        $("#step2").hide();
        $("#step1").show();
    }


}

function getCheckNum() {
    var ajaxTimeoutTest = $.ajax({
        type: "post",
        url: getCheckNumServlet,
        timeout: 9000,
        data: {},
        dataType: "json",
        success: function(msg) {
            if (msg.code == "0000") {
                $("#step1").hide();
                $("#step2").show();
                $(".loading_img").show();
                $('#checkNumber').text(msg.data.validate_data);
                validate_data = msg.data.validate_data;
                $(".loading_img").hide();
                initStep2View();
            } else if (msg.code == "0012" || msg.code == "0131") {
                if (msg.msg) {
                    $.alert(msg.msg, "提示", function() {
                        showStepN(0);
                    });
                } else {
                    $.alert("当前用户没有查询权限。", "提示", function() {
                        showStepN(0);
                    });
                }

            } else if (msg.msg) {
                $.alert(msg.msg);
            } else {
                $.alert("人脸识别字符串获取失败");
            }


        },
        complete: function(XMLHttpRequest, status) {　　　
            if (status == 'timeout') {　　　　　
                ajaxTimeoutTest.abort();
                location.href = "./fail.html#3";
                $(".loading_img").hide();　　　　
            }
        }
    });
}


// 拍摄视频按钮事件
function shootingVideo() {
    /*******调试*************/
/*        $("#step2").hide();
        $("#step3").show();
        setStepLoader(1);
        //        window.step++;  // 跳过视频验证
        youtuDetect("0001");
        return;*/
    /********调试*************/
    var sourceType = "camera";
    var camera = "front"; // front 前置摄像头 back 后置摄像头
    var maxDuration = 7; // $('#max').val();
    //  console.log(sourceType, camera, maxDuration);
    WeixinJSBridge.invoke('chooseVideo', {
        sourceType: sourceType,
        maxDuration: maxDuration,
        camera: camera
    }, function(res) {


        if (res.localId) {
            //            alert(JSON.stringify(res.localId));
            initStepLoader();
            $("#step2").hide();
            $("#step3").show();
            setStepLoader(1); // 开始验证
            localId = res.localId;
            wxUpload(localId);
        } else if (res.errMsg) {
            alert(res.errMsg);
        } else {
            alert("拍摄视频失败");
        }


 });


}


//上传文件
function wxUpload(localId) {
    //    alert(appId);
    WeixinJSBridge.invoke('uploadVideo', {
        appId: appId,
        isShowProgressTips: 0,
        localId: localId
    }, function(res) {
        //        alert(JSON.stringify(res));
        if (res.err_msg === "uploadVideo:ok") {
            serverId = res.serverId;
            //            alert("调试视频验证");
            youtuDetect();
        } else if (res.err_msg === "uploadVideo:cancel") {
            alert("上传视频被取消");
        } else if (res.errMsg) {
            alert("上传视频失败");
        }
    });

}



// 填充基本信息
function fillStep4Info() {
    $("#step4-name").text($("#name").val());
    $("#step4-sfz").text($("#frId").val());
    $("#step4-phone").text($("#phone").val());
}

// 识别验证视频
function youtuDetect(interId) {
    setStepLoader(step + 1);

    var userPhone = $phone.val();
    id_no = $("#frId").val();
    username = $("#name").val();
    var bankNo = $("#bankNo").val();
    if (window.step == 0 || !seralNo) {
        seralNo = "342648762343_001_" + (new Date()).getTime();
    }
    var param = {
        pkId: "001",
        name: username, // 姓名
        idCard: id_no, // 身份号
        phoneNo: userPhone,
        bankNo: bankNo, // 银行卡号
        step: window.step,
        interId: interId,
        seralNo: seralNo,
        serverId: serverId, // 上传文件是索引
        validate_data: validate_data,
        localId: localId
    };
    $.ajax({
        type: 'post',
        dataType: "json",
        url: youTuDetectServlet,
        data: param,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        success: function(queryData) {
//        alert(youTuDetectServlet + window.step + ":" + JSON.stringify(queryData));

            if (queryData && queryData.code == "0000") {
                setStepLoaderEnd(step+1);
                sessionStorage.setItem("credit_photo", queryData.resp_photo);
                if (window.step == 0) {
                    $("#validate-result").empty();
                }
                processingData(queryData);
                if (queryData.next == "1") {
                    //                    setLocalLoading("下个结果验证");
                    window.step++;
                    youtuDetect(queryData.interId);
                } else {
                    window.step = 0;
                    $("#step3").hide();
                    $("#step4").show();
                    fillStep4Info();
                }
            } else if (queryData.code == "0012" || queryData.code == "0131") {
                if (queryData.msg) {
                    $.alert(queryData.msg, "提示", function() {
                        showStepN(0);
                    });
                } else {
                    $.alert("当前用户没有查询权限。", "提示", function() {
                        showStepN(0);
                    });
                }

                return;
            } else if (queryData && queryData.code) {
                processingData(queryData);
                window.step = 0;
                $("#step3").hide();
                $("#step4").show();
                fillStep4Info();
            } else {
                if (step == 0) { // 人脸识别失败提示
                    if (queryData.resp_msg) {
                        location.href = "./fail.html?errorCode=" + queryData.resp_msg;
                    } else {
                        location.href = "./fail.html#1";
                    }

                } else if (step == 1) {
                    location.href = "./fail.html#2";
                } else if (step == 2) {
                    location.href = "./fail.html#3";
                } else if (step == 3) {
                    // 信用分计算
                    location.href = "./fail.html#4";
                }

            }

        },
        error: function(msg) {
            var errorMsg = "查询失败";
            if (step == 0) {
                errorMsg = "人脸识别失败";
            } else if (step == 1) {
                errorMsg = "黑名单查询失败";
            } else if (step == 2) {
                errorMsg = "手机号、银行卡查询失败";
            } else if (step == 3) {
                errorMsg = "大数据信用分查询失败";
            }
            $.alert(errorMsg, "提示", function() {
                showStepN(0);
                step = 0;
                $(".weui-mask").hide();
                $(".weui-dialog").hide();
            });

        }
    });

}

// 初始化变量
function initValue() {
    $submit_btn = $("#submit_btn");
    errorObject = new errorDialog();
    $phone = $("#phone");

}

// 绑定事件
function bindEvent() {

    $submit_btn.on("touchend", function() {
        setTimeout(submitFuc, 200);
    });
    $("#recording").on("touchstart", shootingVideo);
//  $("#recording").on("touchstart", youtuDetect);

    $("span[data-tostep]").on("touchstart", fhStep);
    $("div[data-effect]").on("touchstart", function() {
        $("div[data-effect]").removeClass("checked-underline");
        $(this).addClass("checked-underline");
        var effectVal = $(this).data("effect");
        if (effectVal == "query") {
            $("#step-query").hide();
            $("#record-box").show();
        } else {
            $("#step-query").show();
            $("#record-box").hide();
        }
    });
    $("#showStep1").on("touchstart", function() {
        $("#step0").hide();
        $("#step1").show();
    });
    // 显示个人资料按钮
    $("#personal-info").on("touchstart", function() {
        showStepN(5);
    });
    /*    // 登出接口 暂不支持手机端
        $(".tuichu_icon").on("touchstart", function() {
            $.post(singOutServert, {}, function(singOutData) {
                location.href = "./loding.html";
            });
        });*/
}
